import json
from sanic import Websocket
from uuid import UUID
from apps.base.hunter import AppError
from modules.xfyun.auth import XFYunAuth
import base64


AUTH_URL = 'wss://tts-api.xfyun.cn/v2/tts'
# 不知道是干啥的
answer = ""
sid = ''


class TtsAuthExt(XFYunAuth):
    """
    用于扩展认知模型的参数
    https://www.xfyun.cn/doc/spark/general_url_authentication.html
    """

    def __init__(self, text: str):
        """
        AudioFile: 语音文件保存路径
        """
        super().__init__(XFYun_URL=AUTH_URL)
        self.domain = "generalv3.5"
        self.text = text
        # 业务参数(business)，更多个性化参数可在官网查看
        self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
        self.Data = {"status": 2, "text": str(base64.b64encode(self.text.encode('utf-8')), "UTF8")}


async def send_tts(tts_ws, wsParam):
    """
    发送数据到chat
    """
    data = {"common": wsParam.CommonArgs,
            "business": wsParam.BusinessArgs,
            "data": wsParam.Data,
            }
    data = json.dumps(data)

    await tts_ws.send_str(data)


async def recv_tts(ws, message) -> bytes:
    try:
        message =json.loads(message)
        code = message["code"]
        sid = message["sid"]
        audio = message["data"]["audio"]
        audio = base64.b64decode(audio)
        status = message["data"]["status"]
        print(message)
        if status == 2:
            print("ws is closed")
            await ws.close()
        if code != 0:
            errMsg = message["message"]
            print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
        else:
            return audio
            # with open('./demo2.pcm', 'ab') as f:
            #     f.write(audio)

    except Exception as e:
        print("receive msg,but parse exception:", e)
